package de.mrapp.ohos_util.view;

import ohos.agp.components.Component;
import ohos.utils.PlainArray;

public class ViewHolder {

    /**
     * The view, the view holder is associated with.
     */
    private final Component parentView;

    /**
     * A sparse array, which maps the resource IDs of already referenced views to the views
     * themselves.
     */
    private PlainArray<Component> views;

    /**
     * Creates a new view holder.
     *
     * @param parentView The view, the view holder is associated with, as an instance of the class {@link
     *                   Component}. The view may not be null
     */
    public ViewHolder(final Component parentView) {
        this.parentView = parentView;
        this.views = null;
    }

    /**
     * Returns the view, the view holder is associated with.
     *
     * @return The view, the view holder is associated with, as an instance of the class {@link
     * Component}. The view may not be null
     */

    public final Component getParentView() {
        return parentView;
    }

    /**
     * Returns the view, which belongs to a specific resource ID. If the view has already been
     * referenced, the view, which is stored by the view holder, will be returned. Otherwise the
     * method <code>findComponentById(int):Component</code> of the parent view, the view holder belongs to, is
     * used to reference the view.
     *
     * @param viewId The resource ID of the view, which should be returned, as an {@link Integer} value.
     *               The ID must be a valid resource ID of a view, which belongs to the given parent view
     * @return The view, which belongs to the given resource ID, as an instance of the class {@link
     * Component} or null, if no view with the given ID is available
     */
    public final Component findComponentById(final int viewId) {
        Component view = null;

        if (views != null) {
            if (views.get(viewId) != null && views.get(viewId).isPresent()) {
                view = views.get(viewId).get();
            }
        } else {
            views = new PlainArray<>();
        }

        if (view == null) {
            view = parentView.findComponentById(viewId);
            views.put(viewId, view);
        }

        return view;
    }

    /**
     * Removes all references, which are stored by the view holder.
     */
    public final void clear() {
        if (views != null) {
            views.clear();
            views = null;
        }
    }
}
